import { useEffect, useState } from "react";
import { addScript } from "@/utils";
import { ALCaptchaEnum } from "@/enum/app";
import { API_USER_VALIDATE_CHART } from "@/api/login";
export const useLoginHooks = (success: (captchaKeyId: string) => void) => {
  const [captchaKeyId, setCaptchaKeyId] = useState("");
  let captcha: any = null;
  // 验证结果回调
  const captchaVerifyCallback = async (captchaVerifyParam: string) => {
    const res: any = await API_USER_VALIDATE_CHART({
      captchaStr: captchaVerifyParam,
      sceneId: ALCaptchaEnum.SceneId,
    });
    if (res.success && res.data) {
      setCaptchaKeyId(res.data.captchaKeyId);
      return Promise.resolve({
        captchaResult: res.data.success,
      });
    } else {
      return Promise.resolve({
        captchaResult: false,
      });
    }
  };
  const onBizResultCallback = () => {
    console.log(captchaKeyId, "get captchaKeyId");
    success(captchaKeyId);
  };
  const initCaptcha = useEffect(() => {
    let path =
      "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js?t=" +
      Math.random();
    addScript(path, "alicdn.com/captcha-frontend", () => {
      window.initAliyunCaptcha({
        SceneId: ALCaptchaEnum.SceneId, // 场景ID。根据步骤二新建验证场景后，您可以在验证码场景列表，获取该场景的场景ID
        prefix: ALCaptchaEnum.prefix, // 身份标。开通阿里云验证码2.0后，您可以在控制台概览页面的实例基本信息卡片区域，获取身份标
        mode: "popup", //embed 验证码模式。popup表示要集成的验证码模式为弹出式。无需修改
        element: "#captcha-element", // 页面上预留的渲染验证码的元素，与原代码中预留的页面元素保持一致。
        button: "#captchaButton", // 触发验证码弹窗的元素。button表示单击登录按钮后，触发captchaVerifyCallback函数。您可以根据实际使用的元素修改element的值
        captchaVerifyCallback: captchaVerifyCallback, // 业务请求(带验证码校验)回调函数，无需修改
        onBizResultCallback: onBizResultCallback, // 业务请求结果回调函数，无需修改
        getInstance: (getInstance: any) => {
          captcha = getInstance;
        },
        slideStyle: {
          width: 326,
          height: 32,
        }, // 滑块验证码样式，支持自定义宽度和高度，单位为px。其中，width最小值为320 px
        language: "cn", // 验证码语言类型，支持简体中文（cn）、繁体中文（tw）、英文（en）
        immediate: true,
      });
    });
  });
  return {
    initCaptcha,
  };
};
